// MFRC522 读、写卡演示代码
// 使用了pueroyado/MFRC522

#include <cupeMF522.h>

#include <RFID.h>
// 4字节卡序列号，第5字节为校验字节
unsigned char serNum[5];
// 写卡数据
unsigned char writeDate[16] = {'G', 'e', 'e', 'k', '-', 'W', 'o', 'r', 'k', 'S', 'h', 'o', 'p', 0, 0, 0};
// 原扇区A密码，16个扇区，每个扇区密码6Byte
unsigned char sectorKeyA[16][16] = {
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
};
// 新扇区A密码，16个扇区，每个扇区密码6Byte
unsigned char sectorNewKeyA[16][16] = {
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
};

RFID rfid(MF522_CS, MF522_NPD);

void CupeMF522::init()
{
  SPI.setMISO(MF522_MISO);
  SPI.setMOSI(MF522_MOSI);
  SPI.setSCLK(MF522_SCK);
  SPI.begin();

  rfid.init();
}

void CupeMF522::loop()
{
  unsigned char i, tmp;
  unsigned char status;
  unsigned char str[MAX_LEN];
  unsigned char RC_size;
  unsigned char blockAddr; // 选择操作的块地址0～63

  // 找卡
  if (rfid.isCard())
  {
    // 读取卡序列号
    if (rfid.readCardSerial())
    {
      dbLog("\nThe card's number is  : ");
      dbLog("%02X ", rfid.serNum[0]);
      dbLog("%02X ", rfid.serNum[1]);
      dbLog("%02X ", rfid.serNum[2]);
      dbLog("%02X ", rfid.serNum[3]);
      dbLog("%02X ", rfid.serNum[4]);
    }

    // 选卡，返回卡容量（锁定卡片，防止多次读写）
    rfid.selectTag(rfid.serNum);

    // 写数据卡
    blockAddr = 7;                                                                             // 数据块7
    if (rfid.auth(PICC_AUTHENT1A, blockAddr, sectorKeyA[blockAddr / 4], rfid.serNum) == MI_OK) // 认证
    {
      // 写数据
      status = rfid.write(blockAddr, sectorNewKeyA[blockAddr / 4]);
      dbLog("\nset the new card password, and can modify the data of the Sector: ");
      dbLog("%d", blockAddr / 4);
      // 写数据
      blockAddr = blockAddr - 3; // 数据块4
      status = rfid.write(blockAddr, writeDate);
      if (status == MI_OK)
      {
        dbLog("\nWrite card OK!");
      }
    }

    // 读卡
    blockAddr = 7; // 数据块7
    status = rfid.auth(PICC_AUTHENT1A, blockAddr, sectorNewKeyA[blockAddr / 4], rfid.serNum);
    if (status == MI_OK) // 认证
    {
      // 读数据
      blockAddr = blockAddr - 3; // 数据块4
      if (rfid.read(blockAddr, str) == MI_OK)
      {
        dbLog("\nRead from the card ,the data is : ");
        dbLog((char *)str);
      }
    }
    rfid.halt();
  }
}
